package com.xiaozhen.rtmp.controller;

import cn.hutool.crypto.digest.MD5;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xiaozhen.common.core.domain.AjaxResult;
import com.xiaozhen.rtmp.dao.CameraDao;
import com.xiaozhen.rtmp.domain.Camera;
import com.xiaozhen.rtmp.domain.vo.CameraVo;
import com.xiaozhen.rtmp.service.MediaService;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

/**
 * api管理接口
 * 后续可能改为使用数据库
 *
 * @author ZJ
 */
@Api(tags = "管理视频流的接口")
@RestController
public class StreamController {

    @Autowired
    private MediaService mediaService;
    @Autowired
    private CameraDao cameraMapper;

    /**
     * 分页查询
     *
     * @param pageNum
     * @param pageSize
     * @return
     */
    @RequestMapping("page")
    public AjaxResult page(Long pageNum, Long pageSize) {
        if (null == pageNum || pageNum <= 1) {
            pageNum = 1L;
        }
        if (null == pageSize || pageSize <= 10) {
            pageSize = 10L;
        }
        Page<Camera> page = new Page<>();
        page.setCurrent(pageNum);
        page.setSize(pageSize);
        page.addOrder(OrderItem.desc("id"));

        QueryWrapper<Camera> queryWrapper = new QueryWrapper<>();
        Page<Camera> data = cameraMapper.selectPage(page, queryWrapper);
        return AjaxResult.success(data);
    }

    /**
     * 查询所有流
     *
     * @return
     */
    @RequestMapping("list")
    public AjaxResult list() {
        List<Camera> data = cameraMapper.selectList(null);
        List<CameraVo> rData = new ArrayList<>();
        for (Camera camera : data) {
            CameraVo cameraVo = new CameraVo();
            cameraVo.setEnabledFlv(camera.getFlv());
            cameraVo.setEnabledHls(camera.getHls());
            cameraVo.setMode(camera.getFfmpeg() ? "ffmpeg" : "javacv");
            cameraVo.setRemark(camera.getRemark());
            cameraVo.setUrl(camera.getUrl());
            rData.add(cameraVo);
        }
        return AjaxResult.success(rData);
    }

    /**
     * 新增流
     *
     * @param cameraVo
     * @return
     */
    @RequestMapping("add")
    public AjaxResult add(Camera cameraVo) {
        String digestHex = MD5.create().digestHex(cameraVo.getUrl());

        Camera camera = new Camera();
        camera.setMediaKey(digestHex);

        QueryWrapper<Camera> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("media_key", digestHex);
        Integer selectCount = cameraMapper.selectCount(queryWrapper);
        if (selectCount > 0) {
            return AjaxResult.error("数据库里已有此地址");
        }

        camera.setUrl(cameraVo.getUrl());
        camera.setRemark(cameraVo.getRemark());
        int save = cameraMapper.insert(camera);
        return save == 1 ? AjaxResult.success("新增成功") : AjaxResult.error("新增失败");
    }

    /**
     * 编辑流
     *
     * @param camera
     * @return
     */
    @RequestMapping("edit")
    public AjaxResult edit(Camera camera) {
        String digestHex = MD5.create().digestHex(camera.getUrl());
        QueryWrapper<Camera> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("media_key", digestHex);
        Camera selectOne = cameraMapper.selectOne(queryWrapper);
        if (null != selectOne) {
            int res = cameraMapper.update(selectOne, queryWrapper);
        }

        return AjaxResult.success("编辑成功");
    }

    /**
     * 删除流（会停止推流）
     *
     * @param camera
     * @return
     */
    @RequestMapping("del")
    public AjaxResult del(Camera camera) {
        String digestHex = MD5.create().digestHex(camera.getUrl());
        camera.setMediaKey(digestHex);
        QueryWrapper<Camera> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("media_key", digestHex);
        Camera cameraVo = cameraMapper.selectOne(queryWrapper);
        cameraMapper.delete(queryWrapper);
        mediaService.closeForApi(cameraVo);
        cameraMapper.delete(queryWrapper);
        return AjaxResult.success("删除成功");
    }

    /**
     * 停止推流
     *
     * @param camera
     * @return
     */
    @RequestMapping("stop")
    public AjaxResult stop(Camera camera) {
        String digestHex = MD5.create().digestHex(camera.getUrl());
        camera.setFlv(false);
        QueryWrapper<Camera> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("media_key", digestHex);
        int res = cameraMapper.update(camera, queryWrapper);
        Camera cameraVo = cameraMapper.selectOne(queryWrapper);
        mediaService.closeForApi(cameraVo);
        return AjaxResult.success("停止推流成功");
    }

    /**
     * 开始推流
     *
     * @param camera
     * @return
     */
    @RequestMapping("start")
    public AjaxResult start(Camera camera) {
        String digestHex = MD5.create().digestHex(camera.getUrl());
        QueryWrapper<Camera> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("media_key", digestHex);
        Camera cameraVo = cameraMapper.selectOne(queryWrapper);
        boolean playForApi = mediaService.playForApi(cameraVo);

        if (playForApi) {
            Camera cameraEntity = new Camera();
            cameraEntity.setId(cameraVo.getId());
            cameraEntity.setFlv(true);
            int res = cameraMapper.updateById(cameraEntity);
        }

        return playForApi ? AjaxResult.success("开启推流成功") : AjaxResult.error("开启失败");
    }

}
